package com.sscw.tcp.config;


import com.sscw.tcp.utils.ConnectionOptionWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


@Slf4j
@Configuration
@AllArgsConstructor
public class MQTTIoProducerConfig {

    private final MQTTIoProperties mqttIoProperties;


    @Bean
    public MqttClient serverIoConsumer() throws MqttException, InvalidKeyException, NoSuchAlgorithmException {
        ConnectionOptionWrapper connectionOptionWrapper = new ConnectionOptionWrapper(mqttIoProperties.getInstanceId(), mqttIoProperties.getAccessKey(), mqttIoProperties.getSecretKey(), mqttIoProperties.getClientId());
        final MemoryPersistence memoryPersistence = new MemoryPersistence();
        final MqttClient mqttClient = new MqttClient("tcp://" + mqttIoProperties.getDomain() + ":" + mqttIoProperties.getPort(), mqttIoProperties.getClientId(), memoryPersistence);
        mqttClient.setTimeToWait(5000);
        mqttClient.connect(connectionOptionWrapper.getMqttConnectOptions());
        log.info("mqtt终端连接启动成功");
        return mqttClient;
    }

}
